import axios from 'axios'
import _ from 'lodash'
import Vue from 'vue'
import { LoadingPlugin , ToastPlugin } from 'vux'
Vue.use(LoadingPlugin)
Vue.use(ToastPlugin, {position: 'middle'})
var vueInstance = new Vue();

import handleParam from './handleParam'
// import store from '../store/store.js'

let baseURL = '';
if(process.env.NODE_ENV === 'development') {
  baseURL = '/api'
}
const instance = axios.create({
  timeout: 4000,
  baseURL:baseURL
  // headers:{
  //   "Authorization": 
  // }
})
export const post = function (url, body = {}, { loading = true, errorHandler = true, needAuth = true } = {}) {
  let loadingInstance = null
  if (loading) {
    vueInstance.$vux.loading.show({
      text: '加载中'
    })
  }

  return instance.post(`${url}?${handleParam(body)}`).then(function (response) {
    let res = response.data
    vueInstance.$vux.loading.hide();
    if (res.code === 'SUCCESS') {
      return Promise.resolve(res.message || {})
    } else if (res.code === 'ERROR' || res.code === 'INTERNAL_ERROR') {
      return Promise.reject(res.message)
    }
  }).catch(function (error) {
    vueInstance.$vux.loading.hide();
    return Promise.reject(error)
  })
}

export const get = function (url, params,{ loading = true, errorHandler = true,needAuth = true } = {}) {
  let loadingInstance = null
  if (loading) {
    vueInstance.$vux.loading.show({
      text: '加载中'
    })
  }
  return instance.get(url, {params}).then(function (response) {
    let res = response.data
    vueInstance.$vux.loading.hide();
    if (res.code === 'SUCCESS') {
      return Promise.resolve(res.message || {})
    } else if (res.code === 'ERROR') {
      vueInstance.$vux.toast.show({
        text: res.message,
      })
      return Promise.reject(res.message)
    }
  }).catch(function (error) {
     vueInstance.$vux.loading.hide();
     vueInstance.$vux.toast.show({
        text: res.message,
      })
    return Promise.reject(error)
  })
}
